import 'package:flutter/material.dart';
import '../models/heritage_activity.dart';
import '../utils/theme_colors.dart';
import '../widgets/activity_card.dart';
import 'activity_detail_screen.dart';

class UserParticipationScreen extends StatefulWidget {
  const UserParticipationScreen({Key? key}) : super(key: key);

  @override
  State<UserParticipationScreen> createState() => _UserParticipationScreenState();
}

class _UserParticipationScreenState extends State<UserParticipationScreen>
    with TickerProviderStateMixin {
  late TabController _tabController;
  
  // 模拟用户数据
  final List<Map<String, dynamic>> _participationHistory = [
    {
      'activity': HeritageActivity(
        id: '1',
        title: '传统书法体验课',
        description: '学习传统书法技艺',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20calligraphy%20class%20with%20brush%20and%20ink&image_size=landscape_4_3',
        location: '文化中心',
        startDate: DateTime.now().subtract(const Duration(days: 7)),
        endDate: DateTime.now().subtract(const Duration(days: 7)),
        maxParticipants: 20,
        currentParticipants: 18,
        price: 50,
        category: 'education',
        tags: ['书法', '传统文化', '艺术'],
        status: ActivityStatus.completed,
        organizer: '书法老师',
        contactInfo: '联系电话：123-456-7890',
        requirements: '无特殊要求',
        highlights: ['专业指导', '小班教学', '提供材料'],
        rating: 4.8,
        reviewCount: 25,
        isFeatured: true,
        isRecommended: true,
        createdAt: DateTime.now().subtract(const Duration(days: 30)),
        updatedAt: DateTime.now().subtract(const Duration(days: 7)),
      ),
      'participationDate': DateTime.now().subtract(const Duration(days: 7)),
      'status': 'completed',
      'rating': 5,
      'feedback': '非常棒的体验，老师很专业！',
    },
    {
      'activity': HeritageActivity(
        id: '2',
        title: '陶艺制作工坊',
        description: '亲手制作传统陶器',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=pottery%20making%20workshop%20with%20clay%20and%20wheel&image_size=landscape_4_3',
        location: '艺术工作室',
        startDate: DateTime.now().subtract(const Duration(days: 14)),
        endDate: DateTime.now().subtract(const Duration(days: 14)),
        maxParticipants: 15,
        currentParticipants: 12,
        price: 80,
        category: 'craft',
        tags: ['陶艺', '手工制作', '传统工艺'],
        status: ActivityStatus.completed,
        organizer: '陶艺大师',
        contactInfo: '联系电话：123-456-7891',
        requirements: '穿着舒适的衣服',
        highlights: ['专业设备', '一对一指导', '作品带回家'],
        rating: 4.5,
        reviewCount: 18,
        isFeatured: false,
        isRecommended: true,
        createdAt: DateTime.now().subtract(const Duration(days: 45)),
        updatedAt: DateTime.now().subtract(const Duration(days: 14)),
      ),
      'participationDate': DateTime.now().subtract(const Duration(days: 14)),
      'status': 'completed',
      'rating': 4,
      'feedback': '很有趣的体验，学到了很多！',
    },
  ];
  
  final Map<String, dynamic> _userStats = {
    'totalActivities': 12,
    'completedActivities': 10,
    'totalHours': 48,
    'certificates': 3,
    'level': 'Bronze',
    'points': 1250,
    'nextLevelPoints': 2000,
  };
  
  final List<Map<String, dynamic>> _achievements = [
    {
      'title': '文化探索者',
      'description': '参与5个不同类型的文化活动',
      'icon': Icons.explore,
      'color': Colors.blue,
      'unlocked': true,
      'date': DateTime.now().subtract(const Duration(days: 5)),
    },
    {
      'title': '学习达人',
      'description': '完成10小时的学习课程',
      'icon': Icons.school,
      'color': Colors.green,
      'unlocked': true,
      'date': DateTime.now().subtract(const Duration(days: 10)),
    },
    {
      'title': '社区贡献者',
      'description': '在社区发布5篇有价值的内容',
      'icon': Icons.people,
      'color': Colors.orange,
      'unlocked': false,
      'date': null,
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text(
          '我的参与记录',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        backgroundColor: ThemeColors.primary,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.share, color: Colors.white),
            onPressed: _shareProgress,
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.white,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          tabs: const [
            Tab(text: '参与历史'),
            Tab(text: '个人成长'),
            Tab(text: '成就徽章'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildParticipationHistory(),
          _buildPersonalGrowth(),
          _buildAchievements(),
        ],
      ),
    );
  }

  Widget _buildParticipationHistory() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        _buildStatsOverview(),
        const SizedBox(height: 20),
        const Text(
          '参与历史',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 16),
        ..._participationHistory.map((record) => _buildHistoryCard(record)),
      ],
    );
  }

  Widget _buildStatsOverview() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '参与统计',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  icon: Icons.event,
                  label: '总活动数',
                  value: _userStats['totalActivities'].toString(),
                  color: Colors.blue,
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  icon: Icons.check_circle,
                  label: '已完成',
                  value: _userStats['completedActivities'].toString(),
                  color: Colors.green,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  icon: Icons.access_time,
                  label: '学习时长',
                  value: '${_userStats['totalHours']}h',
                  color: Colors.orange,
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  icon: Icons.card_membership,
                  label: '获得证书',
                  value: _userStats['certificates'].toString(),
                  color: Colors.purple,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: const EdgeInsets.symmetric(horizontal: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 24),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryCard(Map<String, dynamic> record) {
    final activity = record['activity'] as HeritageActivity;
    final status = record['status'] as String;
    final rating = record['rating'] as int?;
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ActivityDetailScreen(
                  activityId: activity.id,
                ),
              ),
            );
          },
          borderRadius: BorderRadius.circular(16),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.network(
                        activity.imageUrl,
                        width: 60,
                        height: 60,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            width: 60,
                            height: 60,
                            color: Colors.grey[200],
                            child: Icon(
                              Icons.image_not_supported,
                              color: Colors.grey[400],
                            ),
                          );
                        },
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            activity.title,
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.black87,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 8,
                                  vertical: 4,
                                ),
                                decoration: BoxDecoration(
                                  color: _getStatusColor(status).withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Text(
                                  _getStatusText(status),
                                  style: TextStyle(
                                    fontSize: 12,
                                    fontWeight: FontWeight.w600,
                                    color: _getStatusColor(status),
                                  ),
                                ),
                              ),
                              if (rating != null) ...[
                                const SizedBox(width: 12),
                                Row(
                                  children: List.generate(5, (index) {
                                    return Icon(
                                      index < rating
                                          ? Icons.star
                                          : Icons.star_border,
                                      size: 16,
                                      color: Colors.amber,
                                    );
                                  }),
                                ),
                              ],
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                if (record['feedback'] != null) ...[
                  const SizedBox(height: 12),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.grey[50],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.comment,
                          size: 16,
                          color: Colors.grey[600],
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            record['feedback'],
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[700],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPersonalGrowth() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        _buildLevelProgress(),
        const SizedBox(height: 20),
        _buildGrowthChart(),
        const SizedBox(height: 20),
        _buildSkillProgress(),
      ],
    );
  }

  Widget _buildLevelProgress() {
    final currentPoints = _userStats['points'] as int;
    final nextLevelPoints = _userStats['nextLevelPoints'] as int;
    final progress = currentPoints / nextLevelPoints;
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            ThemeColors.primary.withOpacity(0.1),
            Colors.white,
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: ThemeColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  Icons.military_tech,
                  color: ThemeColors.primary,
                  size: 24,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '当前等级: ${_userStats['level']}',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '$currentPoints / $nextLevelPoints 积分',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          LinearProgressIndicator(
            value: progress,
            backgroundColor: Colors.grey[200],
            valueColor: AlwaysStoppedAnimation<Color>(ThemeColors.primary),
            minHeight: 8,
          ),
          const SizedBox(height: 8),
          Text(
            '距离下一等级还需 ${nextLevelPoints - currentPoints} 积分',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildGrowthChart() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '成长轨迹',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 16),
          Container(
            height: 120,
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Center(
              child: Text(
                '成长图表\n(此处可集成图表库)',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSkillProgress() {
    final skills = [
      {'name': '书法', 'progress': 0.8, 'color': Colors.blue},
      {'name': '陶艺', 'progress': 0.6, 'color': Colors.green},
      {'name': '传统音乐', 'progress': 0.4, 'color': Colors.orange},
      {'name': '民间舞蹈', 'progress': 0.3, 'color': Colors.purple},
    ];
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '技能进度',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 16),
          ...skills.map((skill) => _buildSkillItem(skill)),
        ],
      ),
    );
  }

  Widget _buildSkillItem(Map<String, dynamic> skill) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                skill['name'],
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              Text(
                '${(skill['progress'] * 100).toInt()}%',
                style: TextStyle(
                  fontSize: 12,
                  color: skill['color'],
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          LinearProgressIndicator(
            value: skill['progress'],
            backgroundColor: Colors.grey[200],
            valueColor: AlwaysStoppedAnimation<Color>(skill['color']),
            minHeight: 6,
          ),
        ],
      ),
    );
  }

  Widget _buildAchievements() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        const Text(
          '成就徽章',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 16),
        ..._achievements.map((achievement) => _buildAchievementCard(achievement)),
      ],
    );
  }

  Widget _buildAchievementCard(Map<String, dynamic> achievement) {
    final isUnlocked = achievement['unlocked'] as bool;
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isUnlocked ? Colors.white : Colors.grey[100],
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(isUnlocked ? 0.08 : 0.04),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
        border: isUnlocked
            ? Border.all(
                color: (achievement['color'] as Color).withOpacity(0.3),
                width: 2,
              )
            : null,
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: isUnlocked
                  ? (achievement['color'] as Color).withOpacity(0.1)
                  : Colors.grey[200],
              borderRadius: BorderRadius.circular(16),
            ),
            child: Icon(
              achievement['icon'],
              size: 32,
              color: isUnlocked
                  ? achievement['color']
                  : Colors.grey[400],
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  achievement['title'],
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: isUnlocked ? Colors.black87 : Colors.grey[500],
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  achievement['description'],
                  style: TextStyle(
                    fontSize: 12,
                    color: isUnlocked ? Colors.grey[600] : Colors.grey[400],
                  ),
                ),
                if (isUnlocked && achievement['date'] != null) ...[
                  const SizedBox(height: 8),
                  Text(
                    '获得时间: ${achievement['date'].month}/${achievement['date'].day}',
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey[500],
                    ),
                  ),
                ],
              ],
            ),
          ),
          if (isUnlocked)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.green.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                '已获得',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Colors.green[600],
                ),
              ),
            )
          else
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                '未解锁',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[500],
                ),
              ),
            ),
        ],
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'completed':
        return Colors.green;
      case 'ongoing':
        return Colors.blue;
      case 'cancelled':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status) {
      case 'completed':
        return '已完成';
      case 'ongoing':
        return '进行中';
      case 'cancelled':
        return '已取消';
      default:
        return '未知';
    }
  }

  void _shareProgress() {
    // TODO: 实现分享功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('分享功能开发中...'),
      ),
    );
  }
}